from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required
from app.models import MonitorPoint, MonitorData
from app import db
from datetime import datetime, timedelta

bp = Blueprint('monitor', __name__, url_prefix='/monitor')

@bp.route('/')
@login_required
def index():
    points = MonitorPoint.query.all()
    return render_template('monitor/index.html', points=points)

@bp.route('/point/add', methods=['GET', 'POST'])
@login_required
def add_point():
    if request.method == 'POST':
        name = request.form.get('name')
        location = request.form.get('location')
        description = request.form.get('description')
        
        point = MonitorPoint(
            name=name,
            location=location,
            description=description
        )
        db.session.add(point)
        db.session.commit()
        flash('监控点添加成功', 'success')
        return redirect(url_for('monitor.index'))
    
    return render_template('monitor/add_point.html')

@bp.route('/point/<int:point_id>')
@login_required
def view_point(point_id):
    point = MonitorPoint.query.get_or_404(point_id)
    # 获取最近24小时的数据
    recent_data = MonitorData.query.filter_by(point_id=point_id)\
        .filter(MonitorData.timestamp >= datetime.utcnow() - timedelta(hours=24))\
        .order_by(MonitorData.timestamp.desc())\
        .all()
    return render_template('monitor/view_point.html', point=point, data=recent_data)

@bp.route('/data/<int:point_id>/add', methods=['GET', 'POST'])
@login_required
def add_data(point_id):
    point = MonitorPoint.query.get_or_404(point_id)
    if request.method == 'POST':
        data = MonitorData(
            point_id=point_id,
            dissolved_oxygen=float(request.form.get('dissolved_oxygen')),
            ph_value=float(request.form.get('ph_value')),
            temperature=float(request.form.get('temperature')),
            ammonia_nitrogen=float(request.form.get('ammonia_nitrogen')),
            turbidity=float(request.form.get('turbidity'))
        )
        db.session.add(data)
        db.session.commit()
        flash('数据添加成功', 'success')
        return redirect(url_for('monitor.view_point', point_id=point_id))
    
    return render_template('monitor/add_data.html', point=point)

@bp.route('/point/<int:point_id>/delete', methods=['POST'])
@login_required
def delete_point(point_id):
    point = MonitorPoint.query.get_or_404(point_id)
    # 删除关联的监控数据
    MonitorData.query.filter_by(point_id=point_id).delete()
    db.session.delete(point)
    db.session.commit()
    flash('监控点已删除', 'success')
    return redirect(url_for('monitor.index'))

@bp.route('/data/<int:data_id>/delete', methods=['POST'])
@login_required
def delete_data(data_id):
    data = MonitorData.query.get_or_404(data_id)
    point_id = data.point_id
    db.session.delete(data)
    db.session.commit()
    flash('数据已删除', 'success')
    return redirect(url_for('monitor.view_point', point_id=point_id)) 